<?php
namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use Phalcon\Di;
use StarCloud\Library\Exception;
use StarCloud\Library\HttpCurl;

class Xmly
{
    use HttpCurl;
    /* @var $httpClient HttpClient */
    private $httpClient = null;

    private $appId = 10007;
    private $privateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDDMTYRMYsrUvT5ovE2ogPKxNC+C3uOIfUcQ2VmirXWwHw5xeF4l3xtK0ROOe7Yh0kZl/bdrCzdt/pBkS5rhQnpUEYMniq1CvV9onAZNzCEWZgTtA9y+OnE4UDw0WOlkJLPHzIYWQW/gQu+4ZHAO9oZqvCOM+dxe8OzEKQDGxf9FROY0AMnrcy04dyVOyPxOXWJ5L3M9hWYoX/lgC3hqmoDqBaY0igEAwGk66stC4Qu3JRF0uEc8GIf/HWj2ae6mW4k56ZqfTRNNtGZgCYsbUmpNJnrxlPcafcc6McyV6Vw9zOCWmPXByRLJBzHLXd4f7iUQe5qrFEds7P48oUhBQeHAgMBAAECggEAQ7yVLbxKtnswZl1EZhgtRrWsVvc3JmjkXa2Jx98FIYRk18uy5h1z4ZKtPpReLagtFwOkeOLiIwNQhmZyfH+Lo/rmhERzP6aQ8MtpKWb8oEFTRCstXVHCFj+xQKD5eqBEQjpqMQbbtsx6ngA7i0F5+4RVvJOIktpHXKG+uREy7vFA1I22J5DIwa58z7xLr9najbgllzMScxKAdRZzBVbWeLzMTUJoSBVCUirMopqZUUsVLL1wq9kLDzh3PIh1bEYWZ6FFz0GHkReZOe1Oy0a/BFk6hG7G0/gfk6tcSByBPVFtZYEvxTlg4yqhlsSl0Rsh/+rGvS4DZiZjwkSCzaklKQKBgQDyhdbRZVmvx0reZgC0FHU9HIKYce2v+pFLmqFR+4Zmxo3aCjzd1CfAULyEVRUFgmunHtoTy5I/GBjTCadVTEZwKaggp+5OOXJ5uNwejDDfkVZuTli7/NzcIiTb3WAtz3dwnD2RdMhKQM8dPGK6CLTWwiJk1oEwp/syNC9kIIuzzQKBgQDOCgqIP6rLH7vFzLOSUOQGonW0qnAat4xDporL312z7qTHDYAN8w464q+70KTJcEWsvCS93B1v60UevF+1IOAusLOugGPvjyfbGLOwuK2rzlEncVWO7WtdR+1mIcDZJTkWN9ZduEOIdeEYg+OktaYspsoPxpw+xV8/BevgJyO8owKBgQCCN/TpSAcJB/QeSBy2lImCv60rl3itVdfwBV37PBelVZVS7s5RuZmCfJdMYra/15BgEoO7v0GOWSzzG6radPMZRHS+3AxruhLKYsTmLhYL5OjIn46rmZEpLbgmyc3bqxsRvwKb+F2W6QeMRiEojIY1DdYT2M1TR87r3PNZStRYPQKBgD/a3s7BJJaVPCWePlzvUuw3d1FJrTqqff8NY2Cx1iGIqWrDZVdtZ5CaZqpHjHqdoApbuOtah4kDGkXfTa4eBTyTKOzA/7fj3w9JBY+UfMaNR5t4xXJpZGfhfdK0TUc/AQVAwuAC1nM5TUzCu091uI2IF4FyJURS+STYGfU7TBkPAoGBAOBfB1uuXJd82iiSGhUelZdrU9UAlfwblxaKm73djrTbUEyNUSTJRV4jpUkw0axySqomWdMMQGCfHCGfAGW2+G/QUjlPvoT9VhyNO/HeycY9O1AAEY7HoXLT5j2BjU7irDxGqTZfAyFoikZNbDwBd+pabC5re2gIUApqDN9k3sbO';

    public function __construct()
    {
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    public function sign($body)
    {
        ksort($body);

        $str = "";
        foreach ($body as $key => $value) {
            if (is_array($value)) {
                $value = json_encode($value, JSON_UNESCAPED_UNICODE);
            }
            if (empty($str)) {
                $str .= "{$key}={$value}";
            } else {
                $str .= "&{$key}={$value}";
            }
        }

        openssl_sign($str, $signature, $this->getPrivateKey(), OPENSSL_ALGO_SHA256);

        return base64_encode($signature);
    }

    public function getPrivateKey()
    {
        $privateKey = chunk_split($this->privateKey, 64, "\n");
        $privateKey = "-----BEGIN PRIVATE KEY-----\n" . $privateKey . "-----END PRIVATE KEY-----\n";

        return $privateKey;
    }


    public function createKeyword($keyword, $uid)
    {
        $url = "https://koc.ximalaya.com/koc-center/open/gateway";

        $body = [
            'appId' => $this->appId,
            'method' => 'koc.alias.apply',
            'timestamp' => date('Y-m-d H:i:s'),
            'bizContent' => json_encode([
                'searchWord' => $keyword,
                'albumId' => $uid
            ], JSON_UNESCAPED_UNICODE),
        ];
        $body['sign'] = $this->sign($body);

        $response = $this->httpClient->sendPostRequestUrlEncode($url, $body);

        $result = json_decode($response->getBody()->getContents(), true);

        if (isset($result['code']) && $result['code'] == 0) {
            return true;
        } else {
            throw new Exception(9999, $result['msg']);
        }
    }
}